package com.shaoman.customer.helper

import android.annotation.SuppressLint
import android.content.Context
import android.content.SharedPreferences
import android.util.Log
import com.google.gson.Gson
import com.google.gson.JsonParser

/**
 * Created by liulei
 * 2019/11/11 9:39
 * 本地持久化的操作
 * 考虑做下多线程些处理和效率的优化
 */
object DataSaveImpl : DataSave {

    private val gson: Gson = Gson()

    fun getGson(): Gson {
        return gson
    }

    private val SPNAME = "shaoman_app_persist"
    private var sp: SharedPreferences? = null

    init {
        Log.e("leilei", "DataSaveImpl initEd ......")
        sp = myAppContext().getSharedPreferences(SPNAME, Context.MODE_PRIVATE)
    }

    @SuppressLint("CommitPrefEdits")
    @Suppress("UNCHECKED_CAST")
    override fun save(key: String?, value: Any?) {
        val editor = sp?.edit()
        when (value) {
            is Boolean -> editor!!.putBoolean(key, value)
            is Float -> editor!!.putFloat(key, value)
            is Int -> editor!!.putInt(key, value)
            is Long -> editor!!.putLong(key, value)
            is String -> editor!!.putString(key, value)
            is Set<*> -> {
                val actualVal = value as Set<String>
                editor!!.putStringSet(key, actualVal)
            }
            is Any -> {
                val str = gson.toJson(value)
                editor!!.putString(key, str)
            }
        }
        editor!!.apply()
    }

    override fun get(key: String?, type: Class<*>?): Any? {
        var obj: Any? = null
        when (type) {
            Boolean::class.java -> obj = sp?.getBoolean(key, false)
            Float::class.java -> obj = sp?.getFloat(key, 0.0f)
            Int::class.java -> obj = sp?.getInt(key, 0)
            Long::class.java -> obj = sp?.getLong(key, 0L)
            String::class.java -> obj = sp?.getString(key, "")
            Set::class.java -> obj = sp?.getStringSet(key, null)
            Double::class.java -> obj = sp?.getFloat(key, 0f)
            else -> {
                val str = sp?.getString(key, null)
                if (!str.isNullOrBlank()) {
                    try {
                        Log.e("Gson", "str=$str")
                        JsonParser.parseString(str).let {
                            if (it.isJsonObject) {
                                obj = gson.fromJson(str, type)
                            }
                        }
                    } catch (ex: Throwable) {
                        Log.e("Gson_error", ex.message ?: "null")
                    }
                }
            }
        }
        return obj
    }

}